package com.asia5b.a5mall.goods.activity

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.TextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.adapter.GoodsCompKeyAdapter
import com.asia5b.a5mall.goods.adapter.GoodsCompValueAdapter
import com.asia5b.a5mall.goods.adapter.SearchGoodsAdapter
import com.asia5b.a5mall.goods.databinding.ActivitySearchgoodsBinding
import com.asia5b.a5mall.goods.fragment.GoodsSelectorFragment
import com.asia5b.a5mall.goods.widget.SearchGoodsHelper
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.logic.viewmodel.goods.SearchGoodsActivityVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.goods.GoodsSelectorModel
import com.asia5b.a5mall.middleware.model.goods.SelectorKeyBean
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.asia5b.a5mall.middleware.widget.refresh.AnimationHelper
import com.asia5b.a5mall.middleware.widget.refresh.AutoRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.activity_searchgoods.*

/**
 * Created by zhangyuncai on 2020/1/11.
 * 搜索商品展示列表
 */
@Route(path = ActCons.SearchGoodsActivity)
class SearchGoodsActivity : SimpleActivity<SearchGoodsActivityVM, ActivitySearchgoodsBinding>() {
    override val viewModelClazz: Class<SearchGoodsActivityVM>
        get() = SearchGoodsActivityVM::class.java

    override fun getDataBinding(): ActivitySearchgoodsBinding {
        return ActivitySearchgoodsBinding.inflate(layoutInflater)
    }
    override var sIsDark = true


    val mRecyclerView by lazy { rv_searchgoods }
    var mDatas = arrayListOf<AbsGoodsModel>()
    lateinit var mAdapter: SearchGoodsAdapter

    //搜索商品数据参数
    val params = HashMap<String, Any>()

    //搜索商品关键词
    val etSearch by lazy { et_shop_keyword }

    //右边侧边栏
    val drawerlayout by lazy { drawerlayout_searchgoods }
    lateinit var goodsSelectorFragment: GoodsSelectorFragment

    fun getPopupComp(): PopupWindow {
        val view = View.inflate(mActivity, R.layout.popup_goodscomp, null)
        val popupWindow = PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true)
        val view_goodscomp_bg = view.findViewById<View>(R.id.view_goodscomp_bg)
        view_goodscomp_bg.setOnClickListener {
            popupWindow.dismiss()
        }
        val rb_goodscomp_all = view.findViewById<TextView>(R.id.rb_goodscomp_all)
        rb_goodscomp_all.isSelected = TextUtils.equals("${params.get("sort")}", "def_asc")
        rb_goodscomp_all.setOnClickListener {
            popupWindow.dismiss()
            params.put("sort", "def_asc")
            //todo 记录上次排序
            ll_shopall_zonghe.tag = "def_asc"
            getDatas(1)
        }
        val rb_goodscomp_grade = view.findViewById<TextView>(R.id.rb_goodscomp_grade)
        rb_goodscomp_grade.isSelected = TextUtils.equals("${params.get("sort")}", "grade_asc")
        rb_goodscomp_grade.setOnClickListener {
            popupWindow.dismiss()
            params.put("sort", "grade_asc")
            //todo 记录上次排序
            ll_shopall_zonghe.tag = "grade_asc"
            getDatas(1)
        }
        popupWindow.isOutsideTouchable = true
        popupWindow.setOnDismissListener {
        }
        return popupWindow
    }

    fun getPopupScreen(selectorKeyBean: SelectorKeyBean): PopupWindow {
        val view = View.inflate(mActivity, R.layout.popup_goodscreen, null)
        val popupWindow = PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true)
        val view_goodscomp_bg = view.findViewById<View>(R.id.view_goodscomp_bg)
        view_goodscomp_bg.setOnClickListener {
            popupWindow.dismiss()
        }
        popupWindow.isOutsideTouchable = true

        var mMainValueRecyclerView = view.findViewById<RecyclerView>(R.id.rv_goodscomp_value)    //主要4个
        var mMainValueAdapter = GoodsCompValueAdapter(selectorKeyBean)
        mMainValueAdapter.selectSelectorBean = SearchGoodsHelper.getSelectorBean(selectorKeyBean, params)

        var mMainResetButton = view.findViewById<TextView>(R.id.tv_goodsscreen_reset) //重置
        var mMainSureButton = view.findViewById<TextView>(R.id.tv_goodsscreen_sure)  //确定

        mMainValueRecyclerView.run {
            layoutManager = GridLayoutManager(mActivity, 2)
            adapter = mMainValueAdapter
            if (itemDecorationCount == 0) {
                addItemDecoration(GridSpacingItemDecoration(2, DisplayUtils.dip2px(mActivity, 5f), true))
            }
        }

        //重置
        mMainResetButton.setOnClickListener {
            mMainValueAdapter.selectSelectorBean = null
            mMainValueAdapter.notifyDataSetChanged()
        }
        //确定
        mMainSureButton.setOnClickListener {
            popupWindow.dismiss()

            if (selectorKeyBean.isBrand()) {//品牌
                if (mMainValueAdapter.selectSelectorBean == null) {
                    params.remove("brand")
                } else {
                    params.put("brand", mMainValueAdapter.selectSelectorBean?.value?:"")
                }
            } else if (selectorKeyBean.isCate()) {//分类
                if (mMainValueAdapter.selectSelectorBean == null) {
                    params.remove("category")
                } else {
                    params.put("category", mMainValueAdapter.selectSelectorBean?.value?:"")
                }
            } else {//其他
                if (mMainValueAdapter.selectSelectorBean == null) {
                    if (params.containsKey("prop")) {
                        var prop = "${params.get("prop")}"
                        val propStringList = prop.split("@")
                        val stringBuffer = StringBuffer()
                        for (s in propStringList) {
                            if (s.contains(selectorKeyBean.key)) {
                            } else {
                                stringBuffer.append(s)
                                stringBuffer.append("@")
                            }
                        }
                        params.put("prop", stringBuffer.toString().removeSuffix("@"))
                    }
                } else {
                    var newProp = ""
                    if (params.containsKey("prop")) {
                        newProp = "${params.get("prop")}"
                    }
                    params.put("prop", "${newProp}@${selectorKeyBean.key}_${mMainValueAdapter.selectSelectorBean?.value?:""}")
                }

            }
            getDatas(1)
        }
        popupWindow.setOnDismissListener {
            mMainKeyAdapter.selectPosition = -1
            mMainKeyAdapter.notifyDataSetChanged()
        }
        return popupWindow
    }

    val mMainKeyRecyclerView: RecyclerView by lazy { rv_searchgoods_screen }   //主要4个
    lateinit var mMainKeyAdapter: GoodsCompKeyAdapter

    /**
     * 设置主要/常用 的4个筛选条件
     */
    fun setMainKeyRecyclerView(list: ArrayList<SelectorKeyBean>) {
        //常用筛选
        mMainKeyAdapter = GoodsCompKeyAdapter(list, params)
        mMainKeyRecyclerView.run {
            layoutManager = GridLayoutManager(mActivity, 4)
            adapter = mMainKeyAdapter
            if (itemDecorationCount == 0) {
                addItemDecoration(GridSpacingItemDecoration(4, DisplayUtils.dip2px(mActivity, 5f), true))
            }
        }
        //主要/常用 的4个筛选条件
        mMainKeyAdapter.setOnItemClickListener { adapter, view, position ->
            val selectorKeyBean = mMainKeyAdapter.getItem(position) as SelectorKeyBean
            mMainKeyAdapter.selectPosition = position
            mMainKeyAdapter.notifyDataSetChanged()
            getPopupScreen(selectorKeyBean).showAsDropDown(mMainKeyRecyclerView)
        }
    }


    /**
     * 每次进入界面获取初始查询参数
     */
    fun getParams(intent: Intent) {
        params.clear()
        //获取关键词
        var keyWord = intent.getStringExtra("keyword")
        //获取分类
        var category = intent.getIntExtra("category", 0)
        if (!TextUtils.isEmpty(keyWord)) {
            params.put("keyword", keyWord!!)
        }
        if (category != 0) {
            params.put("category", category)
        }
        //默认升序
        params.put("sort", "def_asc")
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.run {
            getParams(intent)
            mViewModel.searchGoodsSelector(params)
            getDatas(1)
        }
    }

    override fun initView() {

        mSmartRefreshLayout=mDataBinding.autoSearchgoods
        //全部筛选条件
        goodsSelectorFragment = sNewStanceFragment(mActivity, GoodsSelectorFragment::class.java).apply {
            this.params = this@SearchGoodsActivity.params
        }
        supportFragmentManager.beginTransaction()
                .replace(R.id.fl_searchgoods_right_vessel, goodsSelectorFragment)
                .commit()

        setGoodsRecyclerView()

        drawerlayout.addDrawerListener(object : DrawerLayout.DrawerListener{
            override fun onDrawerStateChanged(p0: Int) {
            }

            override fun onDrawerSlide(p0: View, p1: Float) {
            }

            override fun onDrawerClosed(p0: View) {
                clearEmptyKey()
                goodsSelectorFragment.followParams()
                mMainKeyAdapter.notifyDataSetChanged()
            }

            override fun onDrawerOpened(p0: View) {
                clearEmptyKey()
                goodsSelectorFragment.followParams()
            }

        })

    }

    /**
     * 商品控件变阵
     */
    fun setGoodsRecyclerView() {
        val selected = iv_shop_multi.isSelected
        if (selected) {
            mAdapter = SearchGoodsAdapter(mDatas, true)
            val gridLayoutManager = GridLayoutManager(mActivity, 2)!!
            mRecyclerView.run {
                layoutManager = gridLayoutManager
                adapter = mAdapter
                if (itemDecorationCount == 0) {
                    addItemDecoration(GridSpacingItemDecoration(2, DisplayUtils.dip2px(mActivity, 3f), true))
                }
            }
            mAdapter.setEmptyView(newEmptyView(mActivity))

        } else {
            mAdapter = SearchGoodsAdapter(mDatas, false)
            mRecyclerView.run {
                layoutManager = LinearLayoutManager(mActivity)
                adapter = mAdapter
                if (itemDecorationCount == 0) {
                    addItemDecoration(newDivider(mActivity))
                }
            }
            mAdapter.setEmptyView(newEmptyView(mActivity))
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val goods3Model = mAdapter.getItem(position) as AbsGoodsModel
            startGoodsDetailActivity(mActivity,goods3Model.absGoodsId)
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position) as AbsGoodsModel
            val bundel = Bundle()
            bundel.putBoolean("type", true)
            bundel.putSerializable("data", item)
            bundel.putInt("goodsId", item.absGoodsId)
            val dialog = ARouter.getInstance().build(ActCons.GoodsSpecDF).with(bundel).navigation()
            if (dialog != null && dialog is DialogFragment) {
                dialog.show(supportFragmentManager, "GoodsSpecDF")
            }
        }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        getDatas(2)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        getDatas(1)
    }

    override fun initEvent() {
        ll_shop_search_vessel.setOnClickListener {
            push(ActCons.SearchKeyActivity)
        }

        ll_shopall_zonghe.setOnClickListener {


            if (tv_shopall_zonghe.isSelected) {
                getPopupComp().showAsDropDown(it)
            } else {
                val tag = ll_shopall_zonghe.getTag()
                if (TextUtils.equals("${tag}", "grade_asc")) {
                    params.put("sort", "grade_asc")
                } else {
                    params.put("sort", "def_asc")
                }
                getDatas(1)
            }
        }
        ll_shopall_xiaoliang.setOnClickListener {
            params.put("sort", "buynum_asc")
            getDatas(1)
        }
        ll_shopall_jiage.setOnClickListener {
            if (TextUtils.equals("${params.get("sort")}", "price_asc")) {
                params.put("sort", "price_desc")
            } else {
                params.put("sort", "price_asc")
            }
            getDatas(1)
        }
        ll_shopall_screen.setOnClickListener {
            changeDrawerlayout(true)
        }

        //单双列切换
        iv_shop_multi.setOnClickListener {
            iv_shop_multi.isSelected = !iv_shop_multi.isSelected
            setGoodsRecyclerView()
            AnimationHelper.reclyTypeAnim(iv_shop_multi, iv_shop_multi.isSelected)
        }
    }



    override fun initData() {
        mViewModel.searchGoodsSelector(params)
        getDatas(0)
    }

    fun clearEmptyKey() {
        val iterator = params.iterator()
        while (iterator.hasNext()) {
            val value = iterator.next().value
            if (value == null || TextUtils.isEmpty("${value}")) {
                iterator.remove()
            }
        }
    }

    /*
         keyword    关键字
     category    分类
     brand    品牌
     price    价格
     sort    排序:关键字_排序
     def_asc,def_desc(默认,也就是按照商品id升降序)
     price_asc,price_desc(价格升降序),todo 只有价格升降序,其他默认降序
     buynum_asc,buynum_desc(销量升降序)
     grade_asc,grade_desc(信用升降序)
     prop    属性:参数名_参数值@参数名_参数值
     sellerId    卖家id，搜索店铺商品的时候使用
     */
    fun getDatas(refresh: Int) {
        clearEmptyKey()

        //排序
        //默认价格排序
        iv_shopall_jiage.setImageResource(R.drawable.ic_double_asc)
        tv_shopall_jiage.isSelected = false
        //默认综合排序
        tv_shopall_zonghe.isSelected = false
        //默认销量排序
        tv_shopall_xiaoliang.isSelected = false
        //筛选
        tv_shopall_screen.isSelected = false
        iv_shopall_screen.isSelected = false
        if (params.containsKey("sort")) {
            var sort = "${params.get("sort")}"
            when (sort) {
                "price_asc" -> {//价格升序
                    iv_shopall_jiage.setImageResource(R.drawable.ic_double_asc)
                    tv_shopall_jiage.isSelected = true
                }
                "price_desc" -> {//价格降序
                    iv_shopall_jiage.setImageResource(R.drawable.ic_double_desc)
                    tv_shopall_jiage.isSelected = true
                }
                "def_asc" -> {//默认综合升序
                    tv_shopall_zonghe.isSelected = true
                    tv_shopall_zonghe.setText(getString(R.string.综合))
                }
                "buynum_asc" -> {//销量排序
                    tv_shopall_xiaoliang.isSelected = true
                }
                "grade_asc" -> {//信用升序
                    tv_shopall_zonghe.isSelected = true
                    tv_shopall_zonghe.setText(getString(R.string.信用))
                }
            }
        }
        if (params.containsKey("prop") || params.containsKey("brand") || params.containsKey("category")) {
            tv_shopall_screen.isSelected = true
            iv_shopall_screen.isSelected = true
        }

        if (params.containsKey("keyword")) {
            etSearch.setText("${params.get("keyword")}")
        } else if (params.containsKey("category")) {
            etSearch.setText("${params.get("category")}")
        } else {
            etSearch.visibility = View.GONE
        }

        dddLog("params:" + params)
        mViewModel.getDatas(refresh, params)
    }

  override  fun startObserver()
    {
        mViewModel.goodsListLiveData.observe(this, Observer {
            if(it!=null) {
                getDatasResult(it!!)
            }
        })
        mViewModel.searchGoodsSelectorLiveData.observe(this, Observer {
            searchGoodsSelectorResult(it)
        })
    }

     fun getDatasResult(resultModel: ResultModel<ArrayList<AbsGoodsModel>>) {

        if (resultModel.page <= 1) {
            mAdapter.data.clear()
        }
        if (!resultModel.data.isNullOrEmpty()) {
            mAdapter.addData(resultModel.data!!)
        } else {
            mAdapter.notifyDataSetChanged()
        }
        mDatas = mAdapter.data as ArrayList<AbsGoodsModel>
        mDataBinding.autoSearchgoods.setEnableLoadMore(resultModel.page < resultModel.sumPage)
    }

     fun searchGoodsSelectorResult(goodsSelectorModel: GoodsSelectorModel) {

        /*todo 添加主要的4个筛选条件*/

        goodsSelectorFragment.searchGoodsSelectorResult(goodsSelectorModel)

        setMainKeyRecyclerView(goodsSelectorFragment.mAllDatas)

    }

    /**
     * 抽屉效果的打开
     */
    fun changeDrawerlayout(isOpen: Boolean = true) {
        if (isOpen) {
            drawerlayout.openDrawer(Gravity.RIGHT)
        } else {
            drawerlayout.closeDrawer(Gravity.RIGHT)
        }

    }

    /**
     * 点击返回按钮时
     */
    override fun onBackPressed() {
        if (drawerlayout.isDrawerOpen(Gravity.RIGHT)) {
            changeDrawerlayout(false)
        } /*else if (goodsScreenFragmentVessel.visibility == View.VISIBLE) {
            changeScreen(false)
        } else if (goodsCompFragmentVessel.visibility == View.VISIBLE) {
            changeComp(false)
        } */ else {
            super.onBackPressed()
        }
    }
}

